package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.TopicMapper;
import org.linlinjava.litemall.db.models.Topic;
import org.linlinjava.litemall.db.service.TopicService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic>
        implements TopicService {

    @Override
    public IPage<Topic> queryList(int offset, int limit) {
        Page<Topic> page = new Page<>(offset, limit);
        QueryWrapper<Topic> query = new QueryWrapper<>();
        return baseMapper.selectPage(page, query);
    }

    @Override
    public int queryTotal() {
        return this.baseMapper.selectCount(new QueryWrapper<Topic>());
    }

    @Override
    public IPage<Topic> queryRelatedList(Integer id, int offset, int limit) {
        Page<Topic> page = new Page<>(offset, limit);
        QueryWrapper<Topic> query = new QueryWrapper<>();
        query.eq("id", id);

        List<Topic> topics = baseMapper.selectList(query);
        if (topics.size() == 0) {
            return queryList(offset, limit);
        }
        Topic topic = topics.get(0);

        query = new QueryWrapper<>();
        query.ne("id", topic.getId());

        IPage<Topic> iPage = baseMapper.selectPage(page, query);
        if (iPage.getRecords().size() != 0) {
            return iPage;
        }
        return queryList(offset, limit);
    }

    @Override
    public IPage<Topic> querySelective(String title, String subtitle, Integer pageNo, Integer pageSize) {
        Page<Topic> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Topic> query = new QueryWrapper<>();
        query.like(!StringUtils.isEmpty(title), "title", title);
        query.like(!StringUtils.isEmpty(subtitle), "subtitle", subtitle);
        return baseMapper.selectPage(page, query);
    }
}
